# try:
#     print(stu)
# except BaseException as e:
#     print(e)
# else:
#     print('正常执行')
# print('hello')


import pymysql
host = '127.0.0.1'
port = 3306
user = 'root'
password = 'wjc123456'
database = 'test'
charset = 'utf8'
# 创建数据库的连接对象，连接数据库
db = pymysql.Connect(host=host, port=port, user=user, password=password, database=database, charset=charset)
print('数据库已连接')
# 增
# 准备一下 sql 语句
username = 'wangwu'
pwd = '111'
sql = f"""
insert into users values(null,'{username}','{pwd}')
"""
# 创建游标对象
cursor = db.cursor()
try:
    cursor.execute(sql)
    db.commit()  # 事务提交
    print('数据已插入')
except Exception as e:
    db.rollback()  # 事务回滚
    print(e)

# 改
# 构建sql
username = 'wangwu'
pwd = '123'
sql = f"""
    update users set pwd = '{pwd}' where username = '{username}'
"""
try:
    cursor.execute(sql)
    db.commit()
    print('数据已修改')
except Exception as e:
    db.rollback()
    print(e)

# 删
# 构建 sql
username = 'wangwu'
sql = f"""
    delete from users where username='{username}'
"""
try:
    cursor.execute(sql)
    db.commit()
    print('数据已删除')
except Exception as e:
    db.rollback()
    print(e)

# 查
# 构建 sql
sql = f"""
    select * from users
"""
# 执行 sql
try:
    rows = cursor.execute(sql)
    data = cursor.fetchall()
    print('数据已查询')
except Exception as e:
    print(e)

# 查询了几行
print(rows)
# 打印一下，记录
for row in data:
    print(f'{row[1]}------{row[2]}')


# 关闭游标
cursor.close()
# 关闭数据库
db.close()

